import {
    onBeforeRouteLeave
} from 'vue-router';
console.log(onBeforeRouteLeave, 'onBeforeRouteLeave');
const stateForm = reactive({
    tenantId: null,
    sessionKey: null,
    userId: null,
    mobile: null,
    productId: null,
    getTidUrl: null,
    newUrl: null
});
var currentURL = window.location.href;

function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

stateForm.sessionKey = getParameterByName('sessionKey', currentURL);
stateForm.userId = getParameterByName('userId', currentURL);
stateForm.mobile = getParameterByName('mobile', currentURL);
async function getTenantId() {
    try {
        let firstSlashIndex = stateForm.newUrl.indexOf('/', 8);
        let prefix;

        if (firstSlashIndex !== -1) {
            prefix = stateForm.newUrl.substring(0, firstSlashIndex);
            let protocols = ['http://', 'https://'];
            let protocol = protocols.find(p => prefix.includes(p));

            if (protocol) {
                let result = prefix.substring(protocol.length);
                result = result + '/app_50000005/';
                console.log(result, 'result');
                let data = await post(`/base/api/v1/product/url`, {
                    url: result
                });
                if (data.status === 'success') {
                    stateForm.tenantId = data.data.tenantId;
                    stateForm.productId = data.data.id;
                    console.log(stateForm.tenantId, 'stateForm.tenantId');
                    getUser();
                } else {
                    console.error('获取tenantId失败');
                }
            } else {
                console.error('未找到 `http://` 或 `https://`');
            }
        } else {
            console.error('无法提取前缀');
        }
    } catch (error) {
        console.error('get1TenantId出现错误:', error);
    }
}

function getUser() {
    try {
        let localStorageData = localStorage.getItem('app-user-store');
        if (localStorageData !== null) {
            localStorageData = JSON.parse(localStorageData);
            if (localStorageData.token !== null) {
                console.log('有token调接口校验token的可行性');
                checkToken(localStorageData.token, localStorageData.uuid);
            } else {
                console.log('这里是没有token走的调登录');
                getToken();
            }
        } else {
            getToken();
        }
    } catch (error) {
        console.error('get1User出现错误:', error);
    }
}
async function checkToken(token, uuid) {
    try {
        let params = {
            uuid: uuid,
            token: token,
            appId: 'h5_50000005'
        };
        let result = await post('/base/api/v1/valid', params);
        console.log(result.status, 'checkTokenstatus');

        if (result.data === null) {
            // 如果data为null，则执行getToken操作
            getToken();
        } else {
            let newUserData = {
                uuid: uuid,
                token: token,
                productId: stateForm.productId,
                tenantId: stateForm.tenantId,
                appid: 'h5_50000005'
            };
            localStorage.setItem('app-user-store', JSON.stringify(newUserData));
            window.location.href = stateForm.getTidUrl;
        }

    } catch (error) {
        getToken();
        console.error('checkToken出现错误:', error);
    }
}
async function getToken() {
    try {
        let uuid = '';
        let token = '';
        const params = {
            sessionKey: stateForm.sessionKey,
            mobile: stateForm.mobile,
            appId: 'h5_50000005',
            withTenantIdFlag: false,
            mobileIsUserName: false,
            tenantId: stateForm.tenantId
        };
        let result = await post('/base/api/v1/open/login', params);
        console.log(result.status, 'getTokenstatus');
        if (result.status === 'success') {
            console.log(result, '登陆接口返回');
            uuid = result.data.uuid;
            token = result.data.token;
            let newUserData = {
                uuid: uuid,
                token: token,
                productId: stateForm.productId,
                tenantId: stateForm.tenantId,
                appid: 'h5_50000005'
            };
            localStorage.setItem('app-user-store', JSON.stringify(newUserData));
            window.location.href = stateForm.getTidUrl;
        }else{
            uni.showToast({
                title: '非法账号',
                icon: 'error',
              });
        }
    } catch (error) {
        console.error('getToken出现错误:', error);
        uni.showToast({
            title: '非法账号',
            icon: 'error',
          });
    }
}

async function getNewUrl() {
    try {
        const response = await post('/solution-ppm/api/v2/built-in-system-ppm/wechat_auth_config/query/user_address', {
            userId: stateForm.userId
        });
        const result = response.data; // 获取响应数据
        console.log(result, '跳转地址');
        if (result.productUri) {
            // window.location.href = result.productUri;
            stateForm.getTidUrl = result.appUri;
            stateForm.newUrl = result.productUri;
            getTenantId();
        }
    } catch (error) {
        // 请求失败时调用 getToken
        getToken();

        // 这里处理请求错误
        console.log('get1NewUrl出现错误:', error);
    }
}

getNewUrl();

onBeforeRouteLeave(async (to, from, next) => {
    console.log('想跳登录'); // 打印消息
    await getNewUrl();
    next(false); // 阻止路由跳转
});